const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const connection = require("./util/db")
const R = require("./util/json")
const {formatObject} = require("./util/jsonFormat.js")

const indexRouter = require('./routes/index');
const uploadRouter = require("./routes/upload")

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//去除304 http缓存状态码
app.disable('etag');

app.all("/*", function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With, token');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  const whiteSheet = ["/", "/login"];//设置请求白名单
  let go = false;
  for (let i = 0; i < whiteSheet.length; i++) {
    if (req.url === whiteSheet[i]) {
      go = true;
      break;
    }
  }
  if(go){
    next();//白名单地址直接放行
  }else{
    /*获取token*/
    const token = req.header("token");
    /*根据token获取登录信息*/
    let sql = "select u.*,l.expires from login l left join userinfo u on l.user_id = u.id where token = ?";
    connection.query(sql,[token],function (e,r) {
      if(e){
        throw e
      }
      if(r.length > 0){
        const login = r[0];
        if(login.expires.getTime() > new Date().getTime()){
          req.loginId = login.id;
          req.roleId = login.role_id;
          req.loginInfo = formatObject(login);
          next();
        }else{
          res.json(R.error("token失效",401))
        }
      }else{
        res.json(R.error("未登录",401))
      }
    })
  }
})


app.use('/', indexRouter);
app.use('/upload', uploadRouter);
app.use("/userinfo",require('./routes/userinfo'))
app.use("/role",require('./routes/role'))
app.use("/department",require('./routes/department'))
app.use("/brand",require('./routes/brand'))
app.use("/car",require('./routes/car'))
app.use("/record",require("./routes/record"))
app.use("/apply",require("./routes/apply"))
app.use("/about",require("./routes/about"))


/*设置统一的编码格式*/
app.use(function (req, res, next) {
  req.setEncoding("utf-8");
  res.header("Content-Type","application/json;charset=utf-8")
  next();//放行
})

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
